package com.wan37.logic.handler.server;

import com.wan37.logic.component.Worker;
import com.wan37.logic.db.AsynDBManager;
import com.wan37.logic.domain.entity.RoleDO;
import com.wan37.logic.domain.entity.UserItemDO;
import com.wan37.logic.service.RoleService;
import com.wan37.logic.service.UserService;
import com.wan37.logic.service.cache.RoleServiceCache;
import com.wan37.protobuf.constant.CommonBase;
import com.wan37.logic.domain.vo.RoleVO;
import com.wan37.logic.global.reference.SpringContextHolder;
import com.wan37.logic.handler.WorkerHandler;
import com.wan37.logic.service.cache.SceneServiceCache;
import com.wan37.logic.service.cache.UserServiceCache;
import com.wan37.logic.utils.RouteUtils;
import com.wan37.protobuf.constant.Common;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : luoyong
 * @date : 2020-06-24 13:39
 **/
public class MpHandler implements WorkerHandler {
    private RouteUtils routeUtils;
    private SceneServiceCache sceneServiceCache;
    private UserServiceCache userServiceCache;
    private Long changeMp;
    private RoleVO roleVO;
    private AsynDBManager asynDBManager;
    private RoleService roleService;

    public MpHandler(Long changeMp, RoleVO roleVO) {
        this.changeMp = changeMp;
        this.roleVO = roleVO;
        this.routeUtils = SpringContextHolder.getBean("routeUtils");
        this.sceneServiceCache = SpringContextHolder.getBean("sceneServiceCache");
        this.userServiceCache = SpringContextHolder.getBean("userServiceCache");
        this.asynDBManager = SpringContextHolder.getBean("asynDBManager");
        this.roleService = SpringContextHolder.getBean("roleService");
    }

    @Override
    public void execute(Worker worker) throws Exception {
        long mp = roleVO.getNumberMap().get(CommonBase.MP);
        if (mp < 10000) {
            List<RoleVO> roleVOList = new ArrayList<>();
            roleVOList.add(roleVO);
            roleVO.getNumberMap().put(CommonBase.MP, mp + changeMp);
            routeUtils.sendAoiRoleBroadcastResponse(Common.GAME_ROLE_SUCCESS, sceneServiceCache
                            .getSceneServiceMap().get(userServiceCache.getUserServiceMap()
                                    .get(roleVO.getUserId()).getSceneId()).getUserIdSet(),
                    roleVOList);
            RoleDO roleDO = new RoleDO(roleVO);
            this.asynDBManager.distributeWork(roleVO.getUserId(), () -> roleService.update(roleDO));
        }
    }
}
